package com.cloud.lan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.lan.api.dto.req.ActivityCodeReq;
import com.cloud.lan.api.dto.req.BaseReq;
import com.cloud.lan.dao.LanActivityCodeMapper;
import com.cloud.lan.dao.LanActivityMapper;
import com.cloud.lan.entity.base.BaseResponse;
import com.cloud.lan.entity.base.exceptions.BaseException;
import com.cloud.lan.entity.enums.LanError;
import com.cloud.lan.entity.model.dataobject.LanActivityCodeDO;
import com.cloud.lan.entity.model.dataobject.LanActivityDO;
import com.cloud.lan.service.ILanActivityCodeService;

import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

import javax.annotation.Resource;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import lombok.extern.slf4j.Slf4j;

import static com.cloud.lan.entity.utils.ConstantInterface.Enum.ConstantNumber.ZERO;

/**
 * <p>
 * 兑换码活动码表 服务实现类
 * </p>
 *
 * @author xyqierkang@163.com
 * @since 2022-10-22
 */
@Slf4j
@Service
public class LanActivityCodeServiceImpl extends ServiceImpl<LanActivityCodeMapper, LanActivityCodeDO> implements ILanActivityCodeService {

    @Resource
    LanActivityCodeMapper lanActivityCodeMapper;

    @Resource
    LanActivityMapper lanActivityMapper;

    @Override
    public BaseResponse importActivityCode(@RequestHeader(BaseReq.ut) String token, @RequestParam("file") MultipartFile file, String jsonCode
            , Long activityId) {
        if (CharSequenceUtil.isNotEmpty(jsonCode)) {
            importCodeJson(jsonCode, activityId);
            return BaseResponse.success(CharSequenceUtil.format("json已导入完成"));
        }
        String fileName = file.getOriginalFilename();
        if (ObjectUtil.isNull(fileName)) {
            log.error("#上传xls 失败 fileName空 ：{}", fileName);
            throw new BaseException(LanError.ILLEGAL_PARAMS);
        }
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (!fileType.endsWith(".xls") && !fileType.endsWith(".xlsx")) {
            return BaseResponse.error(LanError.LAN_010010.getCode(), LanError.LAN_010010.getMsg());
        }
        try {
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream(), ZERO.getKey());
            List<ActivityCodeReq> importEvaluateReqs = reader.readAll(ActivityCodeReq.class);
            AtomicReference<Integer> count = new AtomicReference<>(0);
            importEvaluateReqs.forEach(im -> {
                LambdaQueryWrapper<LanActivityCodeDO> qw = new LambdaQueryWrapper<>();
                qw.eq(LanActivityCodeDO::getCode, im.getCode());
                qw.eq(LanActivityCodeDO::getActivityId,activityId);
                if (lanActivityCodeMapper.selectCount(qw) == 0 && CharSequenceUtil.isNotEmpty(im.getCode())) {
                    LanActivityCodeDO lanActivityCodeDO = new LanActivityCodeDO();
                    lanActivityCodeDO.setCode(CharSequenceUtil.trim(im.getCode()));
                    lanActivityCodeDO.setActivityId(activityId);
                    lanActivityCodeMapper.insert(lanActivityCodeDO);
                    count.getAndSet(count.get() + 1);
                }
            });
            LanActivityDO lanActivityDO = lanActivityMapper.selectById(activityId);
            lanActivityDO.setAcCount(lanActivityDO.getAcCount() > 0 ? lanActivityDO.getAcCount() + count.get() : count.get());
            lanActivityMapper.updateById(lanActivityDO);
        } catch (Exception e) {
            log.error("#异步线程 上传xls 失败 ", e);
            return BaseResponse.error(LanError.LAN_010010.getCode(), "导入失败");
        }
        return BaseResponse.success(CharSequenceUtil.format("已导入完成"));
    }

    private void importCodeJson(String jsonCode, Long activityId) {
        if (!JSONUtil.isTypeJSON(jsonCode)) {
            throw new BaseException(LanError.ILLEGAL_PARAMS);
        }
        List<String> codeList = JSONUtil.toList(jsonCode, String.class);
        codeList.forEach(im -> {
            LambdaQueryWrapper<LanActivityCodeDO> qw = new LambdaQueryWrapper<>();
            qw.eq(LanActivityCodeDO::getCode, im);
            if (lanActivityCodeMapper.selectCount(qw) == 0 && CharSequenceUtil.isNotEmpty(im)) {
                LanActivityCodeDO lanActivityCodeDO = new LanActivityCodeDO();
                lanActivityCodeDO.setCode(CharSequenceUtil.trim(im));
                lanActivityCodeDO.setActivityId(activityId);
                lanActivityCodeMapper.insert(lanActivityCodeDO);
            }
        });
    }
}
